/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database_client;

import DataObject.ServerInfo;
import Shared.NodeInfo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

/**
 *
 * @author Backkom
 */
public class TreeInfo {
    
    public JPanel treePanel;
    protected DefaultTreeModel treeModel;
    protected DefaultMutableTreeNode root;
    protected JTree tree;
    
    public TreeInfo() {
        treePanel = new JPanel(new BorderLayout(), true);
        root = new DefaultMutableTreeNode(new NodeInfo("CSDL", "root"));
        treeModel = new DefaultTreeModel(root);
        tree = new JTree(treeModel);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.setShowsRootHandles(false);
        tree.setRowHeight(20);
        tree.setExpandsSelectedPaths(true);
        tree.setBackground(Color.lightGray);
        tree.setCellRenderer(new TreeRenderer());
        JScrollPane scrollTree = new JScrollPane(tree);
        treePanel.add(scrollTree, BorderLayout.CENTER);
    }
    
    public void setTree(ServerInfo svI) {
        root.removeAllChildren();        
        treeModel.setRoot(root);
        CreateTree(svI);
        treePanel.paintAll(treePanel.getGraphics());
    }
    
    private void CreateTree(ServerInfo svI) {
        DefaultMutableTreeNode dbName = new DefaultMutableTreeNode(new NodeInfo(svI.databasesName, "db"), true);
        treeModel.insertNodeInto(dbName, root, 0);
        for (int i = 0; i < svI.getTables().length; i++) {
            String tbName = svI.getTables()[i];
            DefaultMutableTreeNode tb = new DefaultMutableTreeNode(new NodeInfo(tbName, "tb"), true);
            treeModel.insertNodeInto(tb, dbName, 0);
            String[] colName = svI.getColumns(tbName);
            for (int j = 0; j < colName.length; j++) {
                String t = "cl";
                if (colName[j].equalsIgnoreCase(svI.getKey(tbName))) {
                    t = "key";
                }
                String col = colName[j] + " (" + svI.getTypes(tbName)[j] + ')';
                DefaultMutableTreeNode cl = new DefaultMutableTreeNode(new NodeInfo(col, t), false);
                treeModel.insertNodeInto(cl, tb, 0);
            }
            if (i == svI.getTables().length - 1) {
                tree.scrollPathToVisible(new TreePath(tb.getPath()));
            }
        }
    }
}
